<script setup>
import { ref, computed, onMounted } from 'vue'
import {
    Upload,
    Edit,
    Delete,
    Refresh,
    Search,
    Picture,
    VideoCamera,
    VideoPlay,
    VideoPause
} from '@element-plus/icons-vue'
import { uploadFileApi } from '@/api/file'

// 状态管理
const mediaList = ref([])
const selectedItems = ref([])
const currentMedia = ref(null)
const previewVisible = ref(false)
const isPlaying = ref(false)
const videoPlayer = ref(null)
const renameDialogVisible = ref(false)
const newFileName = ref('')
const itemToRename = ref(null)
const viewMode = ref('list')
const filterType = ref('all')
const searchQuery = ref('')
const sortField = ref('name')
const sortOrder = ref('asc')
const currentPage = ref(1)
const pageSize = ref(5)

// 模拟数据 - 实际项目中应该从API获取
const mockMedia = [
    {
        id: 1,
        name: 'beach_sunset.jpg',
        url: 'https://example.com/images/beach_sunset.jpg',
        thumbnail: 'https://example.com/thumbs/beach_sunset.jpg',
        size: 2400000,
        type: 'image',
        format: 'jpeg'
    },
    {
        id: 2,
        name: 'party_2024.mp4',
        url: 'https://example.com/videos/party_2024.mp4',
        thumbnail: 'https://example.com/thumbs/party_2024.jpg',
        size: 156000000,
        type: 'video',
        format: 'mp4'
    },
    {
        id: 3,
        name: 'avatar.png',
        url: 'https://example.com/images/avatar.png',
        thumbnail: 'https://example.com/thumbs/avatar.png',
        size: 1100000,
        type: 'image',
        format: 'png'
    },
    {
        id: 4,
        name: 'tutorial.mp4',
        url: 'https://example.com/videos/tutorial.mp4',
        thumbnail: 'https://example.com/thumbs/tutorial.jpg',
        size: 89000000,
        type: 'video',
        format: 'mp4'
    },
    {
        id: 5,
        name: 'design_final.jpg',
        url: 'https://example.com/images/design_final.jpg',
        thumbnail: 'https://example.com/thumbs/design_final.jpg',
        size: 3700000,
        type: 'image',
        format: 'jpeg'
    },
    {
        id: 6,
        name: 'avatar.png',
        url: 'https://example.com/images/avatar.png',
        thumbnail: 'https://example.com/thumbs/avatar.png',
        size: 1100000,
        type: 'image',
        format: 'png'
    },
    {
        id: 7,
        name: 'tutorial.mp4',
        url: 'https://example.com/videos/tutorial.mp4',
        thumbnail: 'https://example.com/thumbs/tutorial.jpg',
        size: 89000000,
        type: 'video',
        format: 'mp4'
    },
    {
        id: 8,
        name: 'design_final.jpg',
        url: 'https://example.com/images/design_final.jpg',
        thumbnail: 'https://example.com/thumbs/design_final.jpg',
        size: 3700000,
        type: 'image',
        format: 'jpeg'
    }
]

// 加载媒体列表
const loadMediaList = () => {
    // 实际项目中这里应该是API调用
    mediaList.value = [...mockMedia]
}

// 初始化加载媒体列表
onMounted(() => {
    loadMediaList()
})

// 刷新列表
const refreshList = () => {
    loadMediaList()
}

// 处理上传
const handleUpload = async (file) => {
    debugger
    try {
        const formData = new FormData()
        formData.append('file', file.raw)

        // 添加进度条
        const loading = ElLoading.service({
            lock: true,
            text: '文件上传中...',
            background: 'rgba(0, 0, 0, 0.7)'
        })

        const response = await uploadFileApi(formData)

        loading.close()

        if (response.data.code === 200) {
            mediaList.value.unshift(response.data.data)
            ElMessage.success('文件上传成功')
        } else {
            ElMessage.error(`上传失败: ${response.data.message}`)
        }
    } catch (error) {
        console.error('上传出错:', error)
        ElMessage.error('文件上传失败')
        if (process.env.NODE_ENV === 'development') {
            ElMessage.error(error.message)
        }
    }
}

// 处理选择变化
const handleSelectionChange = (selection) => {
    selectedItems.value = selection
}

// 切换选择项 (网格视图用)
const toggleSelect = (item) => {
    const index = selectedItems.value.findIndex(i => i.id === item.id)
    if (index >= 0) {
        selectedItems.value.splice(index, 1)
    } else {
        selectedItems.value.push(item)
    }
}

// 预览媒体
const previewMedia = (item) => {
    currentMedia.value = item
    previewVisible.value = true
    isPlaying.value = item.type === 'video'
}

// 切换视频播放状态
const toggleVideoPlay = () => {
    isPlaying.value = !isPlaying.value
    // 实际项目中应该控制video元素的play/pause
}

// 旋转媒体 (图片)
const rotateMedia = () => {
    // 实际项目中应该实现旋转逻辑
    console.log('旋转媒体:', currentMedia.value.name)
}

// 处理重命名
const handleRename = (item = null) => {
    itemToRename.value = item || selectedItems.value[0]
    newFileName.value = itemToRename.value.name
    renameDialogVisible.value = true
}

// 确认重命名
const confirmRename = () => {
    if (itemToRename.value) {
        itemToRename.value.name = newFileName.value
        renameDialogVisible.value = false
    }
}

// 处理删除
const handleDelete = (item = null) => {
    const itemsToDelete = item ? [item] : selectedItems.value
    const idsToDelete = itemsToDelete.map(i => i.id)

    mediaList.value = mediaList.value.filter(item => !idsToDelete.includes(item.id))
    selectedItems.value = selectedItems.value.filter(item => !idsToDelete.includes(item.id))

    if (currentMedia.value && idsToDelete.includes(currentMedia.value.id)) {
        previewVisible.value = false
        currentMedia.value = null
    }
}

// 清空搜索
const clearSearch = () => {
    searchQuery.value = ''
}

// 格式化文件大小
const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取文件类型
const getFileType = (filename) => {
    const ext = filename.split('.').pop().toLowerCase()
    if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext)) {
        return ext.toUpperCase() + '图像'
    } else if (['mp4', 'mov', 'avi', 'mkv'].includes(ext)) {
        return ext.toUpperCase() + '视频'
    }
    return ext.toUpperCase() + '文件'
}

// 过滤媒体
const filteredMedia = computed(() => {
    let result = [...mediaList.value]

    // 按类型过滤
    if (filterType.value !== 'all') {
        result = result.filter(item => item.type === filterType.value)
    }

    // 搜索过滤
    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(item => item.name.toLowerCase().includes(query))
    }

    // 排序
    if (sortField.value === 'name') {
        result.sort((a, b) => a.name.localeCompare(b.name) * (sortOrder.value === 'asc' ? 1 : -1))
    } else if (sortField.value === 'size') {
        result.sort((a, b) => (a.size - b.size) * (sortOrder.value === 'asc' ? 1 : -1))
    } else if (sortField.value === 'type') {
        result.sort((a, b) => a.type.localeCompare(b.type) * (sortOrder.value === 'asc' ? 1 : -1))
    }

    return result
})

// 排序媒体
const sortMedia = (field) => {
    if (sortField.value === field) {
        sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
    } else {
        sortField.value = field
        sortOrder.value = 'asc'
    }
}
</script>

<template>
    <div class="media-manager-container">
        <!-- 顶部操作栏 -->
        <div class="action-bar">
            <el-upload action="#" :auto-upload="false" :show-file-list="false" :on-change="handleUpload" multiple>
                <el-button type="primary" :icon="Upload">上传</el-button>
            </el-upload>
            <el-button @click="handleRename" :disabled="!selectedItems.length">
                <el-icon>
                    <Edit />
                </el-icon>重命名
            </el-button>
            <el-button @click="handleDelete" :disabled="!selectedItems.length" type="danger">
                <el-icon>
                    <Delete />
                </el-icon>删除
            </el-button>
            <el-button @click="refreshList">
                <el-icon>
                    <Refresh />
                </el-icon>刷新
            </el-button>

            <div class="spacer"></div>

            <el-select v-model="sortField" placeholder="排序" @change="sortMedia">
                <el-option label="按名称排序" value="name"></el-option>
                <el-option label="按大小排序" value="size"></el-option>
                <el-option label="按类型排序" value="type"></el-option>
            </el-select>

            <el-input v-model="searchQuery" placeholder="搜索文件" class="search-input" clearable @clear="clearSearch">
                <template #prefix>
                    <el-icon>
                        <Search />
                    </el-icon>
                </template>
            </el-input>
        </div>

        <!-- 显示方式切换和筛选 -->
        <div class="view-options">
            <el-radio-group v-model="viewMode">
                <el-radio-button label="列表" value="list"></el-radio-button>
                <el-radio-button label="网格" value="grid"></el-radio-button>
            </el-radio-group>

            <el-select v-model="filterType" placeholder="全部" style="width: 80%;">
                <el-option label="全部" value="all"></el-option>
                <el-option label="图片" value="image"></el-option>
                <el-option label="视频" value="video"></el-option>
            </el-select>
        </div>

        <!-- 媒体列表 -->
        <div class="media-list" v-if="viewMode === 'list'">
            <el-table :data="filteredMedia" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="name" label="文件名">
                    <template #default="{ row }">
                        <div class="file-name">
                            <el-icon v-if="row.type === 'image'">
                                <Picture />
                            </el-icon>
                            <el-icon v-else-if="row.type === 'video'">
                                <VideoCamera />
                            </el-icon>
                            <span>{{ row.name }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="缩略图" width="120">
                    <template #default="{ row }">
                        <div class="thumbnail" @click="previewMedia(row)">
                            <img v-if="row.type === 'image'" :src="row.thumbnail || row.url" :alt="row.name" />
                            <div v-else-if="row.type === 'video'" class="video-thumbnail">
                                <el-icon>
                                    <VideoPlay />
                                </el-icon>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="size" label="文件大小" width="120">
                    <template #default="{ row }">
                        {{ formatFileSize(row.size) }}
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="文件类型" width="120">
                    <template #default="{ row }">
                        {{ getFileType(row.name) }}
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 网格视图 -->
        <div class="media-grid" v-else>
            <div v-for="item in filteredMedia" :key="item.id" class="grid-item"
                :class="{ selected: selectedItems.includes(item) }" @click="toggleSelect(item)"
                @dblclick="previewMedia(item)">
                <div class="grid-thumbnail">
                    <img v-if="item.type === 'image'" :src="item.thumbnail || item.url" :alt="item.name" />
                    <div v-else-if="item.type === 'video'" class="video-thumbnail">
                        <el-icon>
                            <VideoPlay />
                        </el-icon>
                    </div>
                </div>
                <div class="grid-name">{{ item.name }}</div>
                <div class="grid-info">
                    {{ formatFileSize(item.size) }} · {{ getFileType(item.name) }}
                </div>
            </div>
        </div>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" :page-size="pageSize" layout="prev, pager, next"
                :total="filteredMedia.length"></el-pagination>
        </div>

        <!-- 预览面板 -->
        <el-dialog v-model="previewVisible" :title="currentMedia?.name" width="70%">
            <div class="preview-content">
                <img v-if="currentMedia?.type === 'image'" :src="currentMedia?.url" :alt="currentMedia?.name"
                    class="preview-image" />
                <video v-else-if="currentMedia?.type === 'video'" controls autoplay class="preview-video">
                    <source :src="currentMedia?.url" :type="'video/' + currentMedia?.format" />
                    您的浏览器不支持视频播放
                </video>
            </div>
            <template #footer>
                <div class="preview-actions">
                    <el-button v-if="currentMedia?.type === 'video'" @click="toggleVideoPlay">
                        <el-icon>
                            <VideoPause v-if="isPlaying" />
                            <VideoPlay v-else />
                        </el-icon>
                        {{ isPlaying ? '暂停' : '播放' }}
                    </el-button>
                    <el-button @click="rotateMedia">
                        <el-icon>
                            <Refresh />
                        </el-icon>旋转
                    </el-button>
                    <el-button @click="handleRename(currentMedia)">
                        <el-icon>
                            <Edit />
                        </el-icon>重命名
                    </el-button>
                    <el-button @click="handleDelete(currentMedia)" type="danger">
                        <el-icon>
                            <Delete />
                        </el-icon>删除
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 重命名对话框 -->
        <el-dialog v-model="renameDialogVisible" title="重命名文件" width="30%">
            <el-input v-model="newFileName" autofocus></el-input>
            <template #footer>
                <el-button @click="renameDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRename">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.media-manager-container {
    padding: 15px;
    height: 100%;
    display: flex;
    flex-direction: column;
    min-height: 100%;
    box-sizing: border-box;
}

.action-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    align-items: center;
}

.spacer {
    flex-grow: 1;
}

.search-input {
    width: 250px;
}

.view-options {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}

.media-list {
    flex-grow: 1;
    overflow: auto;
    margin-bottom: 20px;
}

.media-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 20px;
    flex-grow: 1;
    overflow: auto;
    margin-bottom: 20px;
}

.grid-item {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 10px;
    cursor: pointer;
    transition: all 0.3s;
}

.grid-item:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.grid-item.selected {
    border-color: #409eff;
    background-color: #f5f7fa;
}

.grid-thumbnail {
    width: 100%;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    margin-bottom: 10px;
    overflow: hidden;
}

.grid-thumbnail img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.video-thumbnail {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #000;
    color: #fff;
    font-size: 24px;
}

.grid-name {
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.grid-info {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}

.pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.preview-content {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
}

.preview-image {
    max-width: 100%;
    max-height: 70vh;
}

.preview-video {
    max-width: 100%;
    max-height: 70vh;
}

.preview-actions {
    display: flex;
    justify-content: center;
    gap: 10px;
}

.file-name {
    display: flex;
    align-items: center;
    gap: 8px;
}

.thumbnail {
    width: 100px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    cursor: pointer;
}

.thumbnail img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}
</style>